package vip.meeet;

import vip.meeet.utils.HttpUtil;

import java.io.IOException;

public final class CatHelper {

    /**
     * host:post type
     */
    private static final String CAT_URL_BASE =  "http://%s/_cat/%s?v";

    /**
     * host:port index
     */
    private static final String CAT_COUNT_URL_BASE =  "http://%s/_cat/count/%s?v";
    private static final String CAT_COUNT_ALL_URL_BASE =  "http://%s/_cat/count?v";

    /**
     * 获取ES所用索引
     * @param hostPort 形如：127.0.0.1:9200
     * @return
     * @throws IOException
     */
    public static String indices(String hostPort) throws IOException {
        return cat(hostPort,CatType.INDICES.type);
    }

    public static String health(String hostPort) throws IOException {
        return cat(hostPort,CatType.HEALTH.type);
    }

    public static String allocation(String hostPort) throws IOException {
        return cat(hostPort,CatType.ALLOCATION.type);
    }

    public static String nodes(String hostPort) throws IOException {
        return cat(hostPort,CatType.NODES.type);
    }

    /**
     * 获取指定索引的文档数量
     * @param hostPort
     * @param index
     * @return
     */
    public static String docCount(String hostPort,String index) throws IOException {
        String url = String.format(CAT_COUNT_URL_BASE, hostPort,index);
        return HttpUtil.getContent(url);
    }

    private static String cat(String hostPort,String type) throws IOException {
        String url = String.format(CAT_URL_BASE, hostPort,type);
        return HttpUtil.getContent(url);
    }

    enum CatType{
        HEALTH("health"),
        INDICES("indices"),
        ALLOCATION("allocation"),
        NODES("allocation")
        ;
        private String type;

        CatType(String type) {
            this.type = type;
        }
    }
}
